import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { EmailSettingsDto, EmailSettingsService } from '../proxy';
import snq from 'snq';

@Component({
  selector: 'app-email-setting-group',
  templateUrl: './email-setting-group.component.html',
  styleUrls: ['./email-setting-group.component.less'],
})
export class EmailSettingGroupComponent implements OnInit {
  validateForm: FormGroup;
  emailSettings: EmailSettingsDto;

  get isFormChanged() {
    return snq(() => {
      let isFormChanged = false;
      for (var key of Object.keys(this.validateForm.value)) {
        if (this.validateForm.value[key] != this.emailSettings[key]) {
          return true;
        }
      }
      return isFormChanged;
    });
  }

  constructor(
    private emailSettingsService: EmailSettingsService,
    private fb: FormBuilder,
    private message: NzMessageService
  ) {}

  ngOnInit(): void {
    this.getData();
  }

  private getData() {
    this.emailSettingsService.get().subscribe(res => {
      this.emailSettings = res;
      this.buildForm(res);
    });
  }

  private buildForm(emailSettings: EmailSettingsDto) {
    this.validateForm = this.fb.group({
      defaultFromDisplayName: [emailSettings.defaultFromDisplayName, [Validators.required]],
      defaultFromAddress: [emailSettings.defaultFromAddress, [Validators.required]],
      smtpHost: [emailSettings.smtpHost],
      smtpPort: [emailSettings.smtpPort, [Validators.required]],
      smtpEnableSsl: [emailSettings.smtpEnableSsl],
      smtpUseDefaultCredentials: [emailSettings.smtpUseDefaultCredentials],
      smtpDomain: [emailSettings.smtpDomain],
      smtpUserName: [emailSettings.smtpUserName],
      smtpPassword: [emailSettings.smtpPassword],
    });
  }

  submitForm() {
    if (this.validateForm.invalid || !this.isFormChanged) return;

    this.emailSettingsService.update(this.validateForm.value).subscribe(() => {
      this.message.success('保存成功！');
      this.getData();
    });
  }
}
